<template>
  <div class="home__container">
    <div class="home__nav__container">
      <div class="home__nav__time">时间：{{ nowTime }}</div>
      <div class="home__nav__center">中间内容</div>
      <div class="home__nav__right">
        <NavRight />
      </div>
    </div>
    <div class="home__body__container">
      <div class="body__tool__container">
        <div class="body__tool__left">筛选区域</div>
        <div class="body__tool__right">
          <el-button
            v-if="scrollValue"
            type="primary"
            @click.prevent="toggleScrollValue"
            >停止滚动</el-button
          >
          <el-button
            v-if="!scrollValue"
            type="primary"
            @click.prevent="toggleScrollValue"
            >继续滚动</el-button
          >
          <el-button type="primary" @click="linkToAddOrder(0)"
            >新增工单</el-button
          >
          <el-button @click="linkToAdmin" type="success">后台管理</el-button>
        </div>
      </div>
      <div class="body__table__container">
        <div class="body__scroll__container">
          <div class="scroll__header__container">
            <div
              class="scroll__header__col__container"
              v-for="header in tableHeaderList"
              :key="header.fieldId"
              :style="{
                width: tableColWidth + 'px',
              }"
            >
              {{ header.label || "" }}
            </div>
            <div
              class="scroll__header__col__container"
              :style="{
                width: tableColWidth + 'px',
              }"
            >
              操作
            </div>
          </div>
          <div class="scroll__body__container">
            <vue3-seamless-scroll
              v-model="scrollValue"
              class="scroll"
              wheel
              isWatch
              hover
              :list="filterTableData"
              :singleHeight="178"
              :singleWaitTime="1500"
              :class="{
                'scroll-auto': !scrollValue,
              }"
            >
              <div
                class="scroll__row"
                :class="row.bgColor"
                @click="editRow(row)"
                v-for="(row, rowIndex) in filterTableData"
                :key="row.orderId"
              >
                <div
                  class="scroll__row__col"
                  :style="{
                    width: tableColWidth + 'px',
                  }"
                  v-for="key in tableHeaderKeys"
                  :key="key"
                >
                  <template v-if="key === 'craft_state'">
                    <!-- 工艺 -->
                    <div class="col__craftState__container">
                      <div
                        class="craftState__item__container"
                        v-for="(craftState, craftStateIndex) in row[key].value"
                        :key="craftStateIndex"
                      >
                        <i-ep-right
                          v-if="craftStateIndex > 0"
                          class="item__icon"
                        />
                        <div
                          class="craftState__item"
                          :class="{
                            'craftState__item--finish':
                              Number(craftState.isDone) === 1,
                          }"
                        >
                          {{ craftState.content || "无工艺步骤" }}
                        </div>
                      </div>
                    </div>
                    <div>生产进度：{{ row[key].orderSchedule || "" }}</div>
                  </template>
                  <template v-else-if="key === 'order_state'">
                    <!-- 工单状态 -->
                    <div class="flex__center">
                      <el-tag
                        v-if="
                          Number(row[key].value) === 0 ||
                          Number(row[key].value) === 1
                        "
                        type="info"
                        effect="dark"
                      >
                        {{ row[key].showTableValue || "/" }}
                      </el-tag>
                      <el-tag
                        v-else-if="Number(row[key].value) === 2"
                        type="warning"
                        effect="dark"
                      >
                        {{ row[key].showTableValue || "" }}
                      </el-tag>
                      <el-tag
                        v-else-if="Number(row[key].value) === 3"
                        type="success"
                        effect="dark"
                      >
                        {{ row[key].showTableValue || "" }}
                      </el-tag>
                      <span v-else>{{ row[key]?.showTableValue || "" }}</span>
                    </div>
                  </template>
                  <template v-else-if="row[key]?.formType === 'image'">
                    <!-- 图片，还需处理 -->
                    <div class="flex__center">
                      <template v-if="row[key].showTableValue.length">
                        <div
                          v-if="row[key].showTableValue.length === 1"
                          @click.stop="
                            showBigImageDialogFun(row[key].showTableValue)
                          "
                        >
                          <el-image
                            style="width: 100px; height: 100px"
                            :src="row[key].showTableValue[0]"
                            fit="cover"
                          />
                        </div>
                        <div
                          v-else
                          @click.stop="
                            showBigImageDialogFun(row[key].showTableValue)
                          "
                        >
                          <el-button type="primary">查看详情</el-button>
                        </div>
                      </template>
                      <template v-else>
                        <span>{{ "/" }}</span>
                      </template>
                    </div>
                  </template>
                  <template v-else>
                    <div class="flex__center">
                      {{ row[key]?.showTableValue || "" }}
                    </div>
                  </template>
                </div>
                <div
                  class="scroll__row__col"
                  :style="{
                    width: tableColWidth + 'px',
                  }"
                >
                  <div class="flex__center" style="flex-direction: column">
                    <el-button
                      class="scroll__table__btn"
                      type="primary"
                      @click.stop="editRow(row)"
                      >编辑</el-button
                    >
                    <el-button
                      class="scroll__table__btn"
                      type="danger"
                      @click.stop="delRow(row)"
                      >删除</el-button
                    >
                    <el-button
                      class="scroll__table__btn"
                      type="primary"
                      @click.stop="showOrderDetail(row)"
                      >查看详情</el-button
                    >
                  </div>
                </div>
              </div>
            </vue3-seamless-scroll>
          </div>
        </div>
      </div>
    </div>
    <!-- 查看图片弹窗 -->
    <ShowBigImageDialog ref="ShowBigImageDialogRef" />
    <!-- 查看工单详情弹窗 -->
    <ShowOrderDetailDialog ref="ShowOrderDetailDialogRef" />
  </div>
</template>
<script lang="ts" setup>
import { type OrderFieldItem } from "@/api/order/types";
import { getOrderList, getOrderField, delOrder } from "@/api/order";
import { formatTime } from "@/utils/index";
import { useRouter } from "vue-router";
import { Vue3SeamlessScroll } from "vue3-seamless-scroll"; // 自动滚动插件
import ShowBigImageDialog from "./components/ShowBigImageDialog.vue"; // 查看图片弹窗
import ShowOrderDetailDialog from "./components/ShowOrderDetailDialog.vue"; // 查看工单详情弹窗
const router = useRouter();

const ShowBigImageDialogRef = ref<typeof ShowBigImageDialog | null>(null);
const ShowOrderDetailDialogRef = ref<typeof ShowOrderDetailDialog | null>(null);

const nowTimer = ref<any>(0);
const nowTime = ref<string>("");
const tableHeaderList = ref<OrderFieldItem[]>([]);
const tableHeaderKeys = ref<string[]>([]);
const tableColWidth = ref<number>(0);
const windowWidth = ref<number>(0);
const tableData = ref<any[]>([]);
const scrollValue = ref<boolean>(true);
const orderStateMapNew = ["未生产", "未生产", "生产中", "已完工"]; // 工单状态列表

// 定义自动刷新页面的定时相关变量
const refershTimer = ref<any>(0);
const refershTime = ref<number>(0);

// 查看详情弹窗
const showOrderDetail = (row: any) => {
  ShowOrderDetailDialogRef.value?.handleOpen(row.orderId);
};

// 切换滚动
const toggleScrollValue = () => {
  scrollValue.value = !scrollValue.value;
};

// 编辑表格
const editRow = (row: any) => {
  linkToAddOrder(row.orderId);
};

// 删除工单
const delOrderService = async (ids: string) => {
  let params = {};
  let res = await delOrder(ids, params);
  if (res) {
    getOrderListService();
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  }
};

// 删除表格行
const delRow = (row: any) => {
  ElMessageBox.confirm("您确定要删除该工单吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let ids = String(row.orderId);
      delOrderService(ids);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 查看图片信息
const showBigImageDialogFun = (imgList: string[] = []) => {
  if (imgList.length) {
    ShowBigImageDialogRef.value?.handleOpen(imgList);
  }
};

// 过滤已完成的工单列表
const filterTableData = computed(() => {
  console.log("运行了计算属性");
  return tableData.value.filter((row) => {
    return Number(row["order_state"].value) !== 3;
  });
});

// 判断行的背景色
const editRowBackground = () => {};

// 计算工艺进度
const getOrderSchedule = (contentList: any[] | string) => {
  // console.log("计算进度了  ");
  if (!contentList || !contentList.length) {
    return "/";
  }
  if (contentList === "/") {
    return "/";
  }
  if (Array.isArray(contentList)) {
    let filterList = contentList.filter((elm: any) => elm.isDone == 1);
    let diff = filterList.length
      ? ((filterList.length / contentList.length) * 100).toFixed(2)
      : 0;
    return diff + "%";
  }
};

// 获取表格每行中的列显示数据
// source 是自定义字段对象
const getShowTableValue = (sourceObj: any) => {
  let targetObj = sourceObj || null;
  let targetValue = "/";
  // console.log("targetObj   ++++++++++  ", targetObj);
  if (targetObj) {
    switch (targetObj.formType) {
      case "radio":
        // eslint-disable-next-line no-case-declarations
        const targetOption = targetObj.option;
        // eslint-disable-next-line no-case-declarations
        const findValueObj =
          targetOption.find((elm: any) => elm.value == targetObj.value) || null;
        if (findValueObj) {
          targetValue = findValueObj.label;
        } else {
          targetValue = "/";
        }
        // console.log('targetObj.key ', targetObj.key)
        // console.log('targetObj.value ', targetObj.value)
        break;
      case "checkbox":
        if (Array.isArray(targetObj.value)) {
          let valueList =
            targetObj.value.map((elm: any) => {
              const findObj =
                targetObj.option.find((cElm: any) => cElm.value == elm) || null;
              if (findObj) {
                return findObj.label;
              } else {
                return "无数据";
              }
            }) || [];
          targetValue = valueList.join(",");
        } else {
          targetValue = targetObj.value ? targetObj.value : "/";
        }
        break;
      case "image":
        // 图片需要转成数组
        targetValue = targetObj.value.split(",");
        // console.log("图片的value、--------  ", targetValue);
        break;
      default:
        targetValue = targetObj.value;
        break;
    }
    if (targetObj.key === "order_state") {
      if (
        targetObj.value !== null &&
        targetObj.value !== "" &&
        targetObj.value !== undefined
      ) {
        targetValue = orderStateMapNew[Number(targetObj.value)];
      } else {
        targetValue = targetObj.value || "/";
      }
    }
  } else {
    targetValue = "/";
  }
  return targetValue;
};

// 获取自定义字段列表
const getOrderFieldService = async () => {
  let params = {
    page: 1,
    limit: 0,
    // filter: {
    //   orderId: 0,
    // },
  };
  let res = await getOrderField(params);
  if (res) {
    res.data.list
      .sort((a, b) => {
        return a.sort - b.sort;
      })
      .forEach((elm: OrderFieldItem) => {
        // console.log("自定义字段对象 ", elm.sort);
        if (elm.isListShow > 0) {
          tableHeaderList.value.push(elm);
          tableHeaderKeys.value.push(elm.key);
        }
        // tableHeaderList.value.push(elm);
        // tableHeaderKeys.value.push(elm.key);
      });
    // 获取工单列表
    getOrderListService();
    nextTick(() => {
      computedWidth();
    });
  }
};

// 获取工单列表
const getOrderListService = async () => {
  let params = {
    page: 1,
    limit: 0,
    filter: {},
  };
  let res = await getOrderList(params);
  // console.log("获取了工单列表  ", res.data.list);
  if (res) {
    res.data.list.forEach((elm: any) => {
      // console.log("elm  ", elm);
      if (elm.extra) {
        type pushObject = {
          [key: string]: any;
        };
        let pushObj: pushObject = {};
        tableHeaderKeys.value.forEach((key: string) => {
          // console.log("key  ", key);
          const findObj = elm.extra.find((extra: any) => extra.key === key);
          // console.log("findObj   ", findObj);
          if (findObj) {
            pushObj[key] = findObj;
            pushObj[key].showTableValue = getShowTableValue(findObj);
            if (key === "craft_state") {
              pushObj[key].orderSchedule = getOrderSchedule(findObj.value);
            }
            if (key === "117") {
              // 紧急程度
              pushObj["bgColor"] = Number(findObj.value) === 2 ? "red__bg" : "";
            }

            pushObj["company"] = elm.company;
            pushObj["companyId"] = elm.companyId;
            pushObj["orderId"] = elm.orderId;
            pushObj["status"] = elm.status;
          }
        });
        tableData.value.push(pushObj);
      }
    });
    // console.log("tableData.value  ", tableData.value);
    // tableData.value.forEach((elm) => {
    //   for (let key in elm) {
    //     console.log(
    //       "elm:::::  ",
    //       elm[key].label,
    //       "-->",
    //       elm[key].key,
    //       "-->",
    //       elm[key].showTableValue
    //     );
    //   }
    // });
  }
};

// 时间计时
const initInterval = () => {
  nowTimer.value = setInterval(() => {
    nowTime.value = formatTime();
  }, 1000);
};

// 跳转新增工单页面
const linkToAddOrder = (id: string | number = "") => {
  let param: { [key: string]: any } = {
    path: "/addOrder",
    query: {},
  };
  if (id) {
    param.query.orderId = id;
  }
  router.push(param);
};

// 跳转后台管理系统
const linkToAdmin = () => {
  router.push({
    path: "/dashboard",
  });
};
// 获取自定义字段
getOrderFieldService();

// 计算宽度
const computedWidth = () => {
  let body = document.querySelector("body");
  if (body) {
    windowWidth.value = body.offsetWidth;
    tableColWidth.value =
      windowWidth.value / (tableHeaderList.value.length + 1); // 把操作这一列加进去
  }
};

// 页面定时刷新
const initReferInterval = () => {
  refershTimer.value = setInterval(() => {
    refershTime.value++;
    console.log("计时了");
    if (refershTime.value >= 70) {
      console.log("需要刷新了");
      location.reload();
    }
  }, 1000);
};

onMounted(() => {
  initInterval();
  initReferInterval();
  window.addEventListener("resize", computedWidth);
});
onUnmounted(() => {
  if (nowTimer.value) {
    clearInterval(nowTimer.value);
  }
  if (refershTimer.value) {
    clearInterval(refershTimer.value);
  }
  window.removeEventListener("resize", computedWidth);
});
</script>

<style lang="scss" scoped>
$defaultBg: rgba(47, 84, 235, 0.1); //#0923ce;
$textColor: #fff;
$borderColor: #001c9e;
$textSize: 20px;
$opacityValue: 1;
$hoverBg: rgba(47, 84, 235, 0.5);
.home__container {
  width: 100%;
  height: 100%;
  overflow: auto;
  // background: url("@/assets/images/index/bg_1.png") no-repeat center center;
  background: url("@/assets/images/index/bg_1.png") repeat center center;
  color: #fff;
  .scroll__table__btn {
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .scroll-auto {
    overflow: auto;
  }
  .flex__center {
    height: 100%;
  }
  .red__bg {
    background-color: red;
  }
  .home__nav__container {
    width: 100%;
    height: 80px;
    background: url("@/assets/images/index/bg_header.png") no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    padding-right: 0;
    box-sizing: border-box;
    .home__nav__center {
      height: 100%;
      font-size: 40px;
      line-height: 80px;
      text-align: center;
    }
    .home__nav__time {
      width: 197px;
      flex-shrink: 0;
      height: 45px;
      line-height: 45px;
    }
    .home__nav__right {
      display: flex;
      justify-content: flex-end;
      height: 45px;
    }
  }
  .home__body__container {
    height: calc(100% - 80px);
    box-sizing: border-box;
    padding: 10px;
    overflow: hidden; //auto;
    display: flex;
    flex-direction: column;
    .body__tool__container {
      flex-shrink: 0;
      padding: 5px 0;
      display: flex;
      justify-content: space-between;
      .body__tool__left {
        flex: 1 1 auto;
        max-width: calc(100% - 200px);
        margin-right: 10px;
        word-break: break-all;
      }
      .body__tool__right {
        flex-shrink: 0;
      }
    }
    .body__table__container {
      flex: 1 1 auto;

      .body__scroll__container {
        height: 100%;
        display: flex;
        flex-direction: column;
        .scroll__header__container {
          flex-shrink: 0;
          display: flex;
          box-sizing: border-box;
          border-bottom: 1px solid $borderColor;
          background-color: $defaultBg;
          font-size: $textSize;
          .scroll__header__col__container {
            font-weight: bold;
            box-sizing: border-box;
            padding: 2px 12px;
            border-right: 2px solid $borderColor;
            text-align: center;
            &:last-child {
              border-right: none;
            }
          }
        }
        .scroll__body__container {
          position: relative;
          flex: 1 1 auto;
          .scroll {
            height: 100%;
            overflow: hidden;
            &-auto {
              overflow-y: auto;
            }
            .scroll__row {
              display: flex;
              border-bottom: 1px solid $borderColor;
              background-color: $defaultBg;
              box-sizing: border-box;
              height: 180px;
              cursor: pointer;
              &:hover {
                background-color: $hoverBg;
              }
              .scroll__row__col {
                height: 100%;
                box-sizing: border-box;
                padding: 2px 12px;
                border-right: 2px solid $borderColor;
                word-break: break-all;
                &:last-child {
                  border-right: none;
                }
                .col__craftState__container {
                  display: flex;
                  align-items: center;
                  flex-wrap: wrap;
                  height: 150px;
                  overflow: auto;
                  .craftState__item__container {
                    display: flex;
                    align-items: center;
                    margin-bottom: 5px;
                    .craftState__item {
                      padding: 3px 6px;
                      color: #999; //#fff;
                      border: 1px solid #999; //#001c9e;
                      border-radius: 4px;
                      &--finish {
                        color: #fff;
                        background-color: green;
                      }
                    }
                    .item__icon {
                      margin-left: 5px;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
